import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
// 创建 axios 实例
const service = axios.create({
    baseURL: process.env.NODE_ENV === 'production' ? window.productiontIp : window.developmentIp,
    timeout: window.timeout, // request timeout
})

let lastRequestTime = new Date().getTime();
let lastRequestConfig = null;
//  请求拦截器
service.interceptors.request.use(
    (config) => {
        // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        let requestTime = new Date().getTime();
        let requestConfig = JSON.stringify(config);
        // if (requestTime - lastRequestTime < 500 && lastRequestConfig == requestConfig) {
        //     lastRequestTime = requestTime;
        //     lastRequestConfig = requestConfig;
        //     return Promise.reject(new Error('重复请求'));
        // }
        lastRequestTime = requestTime;
        lastRequestConfig = requestConfig;
        config.headers['Accept'] = 'application/json'
        config.headers['Request-From'] = 'mobile'
        let token = localStorage.getItem('tokenValue') || `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjE2MSwicm5TdHIiOiJvMDJzYkpySVloWDBscVRBT3lDR0xDS2puenAyUDB6OSIsImxvZ2luX25hbWUiOiJseXMiLCJwaG9uZU51bWJlciI6IjE1NzM1NjcwMjI4IiwidXNlcl90eXBlIjoiMDAiLCJDVVJSRU5UX1NZU1RFTV9UWVBFIjoiQkFDS0dST1VORF9TWVNURU0iLCJ1c2VyX25hbWUiOiJseXMiLCJyb2xlX2tleSI6WyIqIl0sIm1lbnVfa2V5IjpbIkhUIiwiKiIsImRlc2Vuc2l0aXphdGlvbiIsIlpaSkciLCJZSExCIiwiQk1MQiIsIkpTTEIiLCJDRExCIiwiWkRMQiIsIkxVR0wiLCJYVEpLIiwiWlhZSCIsIkRTUlciLCJDWlJaIiwiRldKSyIsInVzZXIuYWRkIiwidXNlci5zdGF0dXMiLCJ1c2VyLnVwZGF0ZSIsInVzZXIuZGVsZXRlIiwidXNlci5yZXNwd2QiLCJ1c2VyLmZqIiwidXNlci5qZiIsImRlcC5hZGQiLCJkZXAudXBkYXRlIiwiZGVwLmRlbCIsInJvbGUuYWRkIiwicm9sZS51cGRhdGUiLCJyb2xlLmRlbCIsInJvbGUuZnAiLCJyb2xlLnF4ZnAiLCJtZW51LmFkZCIsIm1lbnUudXBkYXRlIiwibWVudS5kZWwiLCJtZW51LmRhdGEuYWRkIiwibWVudS5kYXRhLnVwZGF0ZSIsIm1lbnUuZGF0YS5kZWwiLCJkaWN0LmFkZCIsImRpY3QudXBkYXRlIiwiZGljdC5kZWwiLCJkaWN0LmRhdGEuYWRkIiwiZGljdC5kYXRhLnVwZGF0ZSIsImRpY3QuZGF0YS5kZWwiLCJyb3V0ZXIuYWRkIiwicm91dGVyLnVwZGF0ZSIsInJvdXRlci5kZWwiLCJvbmxpbmUucXQiLCJqb2IuYWRkIiwiam9iLnN0YXR1cyIsImpvYi5kZWwiLCJqb2Iuenh5YyIsImpvYi5kZWxsb2ciLCJYVFNaIiwicm9sZS5kYXRhc2NvcGUiLCJ1c2VyLnJvbGUiXSwiZGVwYXJ0bWVudCI6MSwidXNlcklkIjoxNjEsImxvZ2luX2lwIjoiMTkyLjE2OC43NC4xIiwiZW1haWwiOiIyNTA3NTg2ODc5QHFxLmNvbSJ9.G6Ry3fWokqoQJ-pXBD_6tdsZODr5GnnxmLQDp5cc8gs`
        if (token) {
            // 如果token不为null，否则传token给后台
            // config.headers[localStorage.getItem('tokenName')] = token
            config.headers['token'] = token
        }

        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        const res = response.data
        //届时根据后端返回success或者code值判断
        // 二进制数据则直接返回
        if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
            return response
        }
        if (res.success === true) {
            // endLoading();
            return res
        } else {
            // endLoading();

            return res
        }

    },
    (error) => {
        // endLoading();
        if (error.message == '重复请求') {
            Message({
                message: '请勿操作过快',
                type: 'error'
            })
        } else if (error.message == `timeout of ${window.timeout}ms exceeded`) {
            Message({
                message: '请求超时',
                type: 'error'
            })
        } else {
            let response = error.response;
            // response && err(response.data)
        }
        //响应错误
        return Promise.reject(error)
    }

)


const postForm = ((url, params) => {
    return new Promise((resolve, reject) => {
        service.post(url, qs.stringify(params), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        })
            .then(res => {
                resolve(res);
            })
            .catch(err => {
                reject(err);
            });
    });
});



//导出
const postBlob = (url, params) => service({
    method: 'post',
    url: url,
    data:params,
    responseType: 'blob',
    headers: {
        'Content-Type': 'application/json'
    }
});
export { postForm, postBlob,service }
